package com.qindian.coupontest;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.qindian.model.CouponModel;
import com.qindian.model.ExchangeModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class GoodsDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final String KEY = "Ypj7fmVAEwyHRcIH6BoBVg3xbGidvnzk";
    private static final String AGENT_ID = "9240";
    private String mType;
    private String mGid;
    private String mUrl;
    private String mDetail;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        Bundle bundle=getIntent().getExtras();
        if (bundle == null) {
            return;
        }
        String pic=bundle.getString("pic");
        mGid = bundle.getString("gid");
        mType = bundle.getString("type");
        mUrl=bundle.getString("url");
        mDetail=bundle.getString("detail");
        String title=bundle.getString("title");
        String originPrice=bundle.getString("originPrice");
        String couponPrice=bundle.getString("couponPrice");

        ImageView imageView=findViewById(R.id.img_goods);
        TextView txtTitle=findViewById(R.id.txt_title);
        TextView txtPrice=findViewById(R.id.txt_price);
        TextView txtCouponPrice=findViewById(R.id.txt_coupon_price);
        TextView txtDetail=findViewById(R.id.txt_detail);
        findViewById(R.id.img_back).setOnClickListener(this);
        findViewById(R.id.txt_exchange).setOnClickListener(this);
        findViewById(R.id.txt_detail).setOnClickListener(this);
        Glide.with(this).load(pic).into(imageView);
        txtTitle.setText(title);
        txtPrice.setText(String.format("价格：%s", originPrice));
        txtCouponPrice.setText(String.format("可抵扣：%s", couponPrice));
        txtDetail.setText("查看商品详情");
        txtDetail.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.txt_exchange:

                AlertDialog.Builder builder = new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("一经兑换后将无法退还,兑换成功后请马上领取")
                        .setNegativeButton("取消兑换", null)
                        .setPositiveButton("确认兑换", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                exchangeCoupon(mType, mGid, "18852996181");
                            }
                        });
                builder.create().show();
                break;
            case R.id.txt_detail:
                switch (mType) {
                    case "tb":
                        if (PackageUtil.checkPackage(mContext,"com.taobao.taobao")) {
                            Intent tbIntent = new Intent();
                            tbIntent.setAction(Intent.ACTION_VIEW);
                            tbIntent.setData(Uri.parse(mUrl));
                            tbIntent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
                            startActivity(tbIntent);
                        } else {
                            Intent webIntent = new Intent(mContext, WebActivity.class);
                            webIntent.putExtra("title", "商品详情");
                            webIntent.putExtra("url", mUrl);
                            startActivity(webIntent);
                        }
                        break;
                    case "jd":
                        if (PackageUtil.checkPackage(mContext,"com.jingdong.app.mall")) {
                            String id = mUrl.substring(mUrl.lastIndexOf("/") + 1, mUrl.lastIndexOf(".html"));
                            Log.e("tag", "onItemClick: " + id);
                            String uri = "openapp.jdmobile://virtual?params=" +
                                    "{\"sourceValue\":\"0_productDetail_97\"," +
                                    "\"des\":\"productDetail\"," +
                                    "\"skuId\":\"" + id + "\"," +
                                    "\"category\":\"jump\"," +
                                    "\"sourceType\":\"homefloor\"}";
                            Intent jdIntent = new Intent();
                            jdIntent.setData(Uri.parse(uri));
                            startActivity(jdIntent);
                        } else {
                            Intent webIntent = new Intent(mContext, WebActivity.class);
                            webIntent.putExtra("title", "商品详情");
                            webIntent.putExtra("url", mUrl);
                            startActivity(webIntent);
                        }
                        break;
                }
                break;
        }
    }
    private void exchangeCoupon(String type, final String gid, String mobile) {

        showLoadingDialog("正在兑换...");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("gid", gid);
        map.put("mobile", mobile);
        map.put("agent_id", AGENT_ID);
        map.put("time", time);

        String prefix = "agent_id=" + AGENT_ID + "&gid=" + gid + "&mobile=" + mobile + "&type=" + type;
        String token = MD5Util.getMD5(prefix + time + KEY);
        map.put("token", token);

        RetrofitHelper.createService().exchangeCoupon(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ExchangeModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ExchangeModel exchangeModel) {
                        switch (exchangeModel.getCode()) {
                            case "000000":
                                getCoupon(gid);
                                break;
                            default:
                                showToast(exchangeModel.getMsg());
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });

    }
    /**
     * 获取优惠券
     *
     * @param id 商品id
     */
    private void getCoupon(String id) {
        showLoadingDialog("正在获取优惠券地址");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("agent_id", AGENT_ID);
        map.put("time", time);
        map.put("id", id);
        String prefix = "agent_id=" + AGENT_ID + "&id=" + id;
        map.put("token", MD5Util.getMD5(prefix + time + KEY));
        RetrofitHelper.createService().getCoupon(mDetail, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Observer<CouponModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CouponModel couponModel) {
                        if (couponModel.getCode().equals("000000")) {
                            String json = new Gson().toJson(couponModel, CouponModel.class);
                            try {
                                JSONObject object = new JSONObject(json).getJSONObject("data");
                                String url = object.getString("coupon_url");
                                switch (mDetail) {
                                    case "jddetail":
                                        Intent jdIntent = new Intent(mContext, WebActivity.class);
                                        jdIntent.putExtra("url", url);
                                        jdIntent.putExtra("title", "京东优惠券");
                                        startActivity(jdIntent);
                                        break;
                                    case "tbdetail":
                                        if (PackageUtil.checkPackage(mContext,"com.taobao.taobao")) {
                                            Intent tbIntent = new Intent();
                                            tbIntent.setAction(Intent.ACTION_VIEW);
                                            tbIntent.setData(Uri.parse(url));
                                            tbIntent.setClassName("com.taobao.taobao", "com.taobao.browser.BrowserActivity");
                                            startActivity(tbIntent);
                                        } else {
                                            showToast("请先安装手机淘宝APP");
                                        }

                                        break;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            showToast(couponModel.getMsg());
                        }
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}
